// pages/goodsDetail/goodsDetail.js
const util = require("../../utils/util.js")
const api = require("../../utils/net.js")
const wxUtils = require("../../utils/wxUtils.js")
const app = getApp()
let lastSaveTime = 0
Page({

  /**
   * 页面的初始数据
   */
  data: {
    images: [],
    isLoading: false,
    orderGoodsId: 0,
    goodsId:0,
    xToast: {
      show: false
    },
    description:"",
    star: 0
  },
  onLoad: function(options) {
    this.setData({
      orderGoodsId: options.id,
      goodsId: options.goodsId
    })
  },
  onChangeRate(e) {
    const index = e.detail.index;
    this.setData({
      'star': index
    })
  },
  uploadCommmentImage: function() {
    let that = this;
    this.uploadIcon(function(imgUrl) {
      var length = that.data.images.length;
      var images = that.data.images
      images[length] = imgUrl
      that.setData({
        images: images
      });
    });
  },
  modifyImage: function(e) {
    var index = e.currentTarget.dataset.index
    let that = this;
    this.uploadIcon(function(imgUrl) {
      var images = that.data.images
      images[index] = imgUrl
      that.setData({
        images: images
      });
    });
  },
  uploadIcon: function(callback) {
    let that = this;
    wx.chooseImage({
      count: 1,
      success: function(res) {
        wx.showLoading({
          title: '正在上传',
        })
        var tempFilePaths = res.tempFilePaths
        let filename = tempFilePaths[0];
        api.get("aliyun/oss/policies", "", {
          onNext: (res) => {
            var accessid = res.accessid;
            var policy = res.policy;
            var signature = res.signature;
            var dirname = res.dir;
            var host = res.host;

            var suffix = '';
            var filePath = '';

            function random_string(len) {
              len = len || 32;
              var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz0123456789';
              var maxPos = chars.length;
              var pwd = '';
              for (var i = 0; i < len; i++) {
                pwd += chars.charAt(Math.floor(Math.random() * maxPos));
              }
              return pwd;
            }

            function get_suffix(filename) {
              var pos = filename.lastIndexOf('.');
              var suffix = '';
              if (pos != -1) {
                suffix = filename.substring(pos);
              }
              return suffix;
            }

            if (filename != '') {
              suffix = get_suffix(filename);
              filePath = dirname + random_string(32) + suffix;
            }
            wx.uploadFile({
              url: host, //仅为示例，非真实的接口地址
              filePath: tempFilePaths[0],
              name: 'file',
              formData: {
                'key': filePath,
                'policy': policy,
                'OSSAccessKeyId': accessid,
                'success_action_status': '200', //让服务端返回200,不然，默认会返回204
                'signature': signature,
              },
              success: function(res) {
                callback(host + "/" + filePath);
                wx.hideToast();
                wx.showToast({
                  title: '上传成功',
                  icon: 'success',
                  duration: 2000
                })
              },
              fail: function(res) {
                wx.showToast({
                  title: JSON.stringify(res),
                  icon: 'none',
                  duration: 2000
                })
              }
            })
          },
          onError: (msg, code) => {
            wx.hideToast()
            wx.showToast({
              title: msg ? msg : `服务器异常，错误代码${code}`,
            })
          }
        })
      }
    })
  },
  save: function (e) {
    if (Date.now() - lastSaveTime < 1000) {
      return
    }
    lastSaveTime = Date.now()
    

    if (this.data.star==0) {
      this.showXToast({ title: "请打分", icon: 'no' })
      return
    }
    let info = e.detail.value
    let description = info.description
    if (util.isEmptyStr(description)) {
      this.showXToast({ title: "评价内容不能为空", icon: 'no' })
      return
    }

    this.showLoading(true)
    let params = {
      star: this.data.star,
      goodsId: this.data.goodsId,
      orderGoodsId:this.data.orderGoodsId,
      description: description,
      imageUrl: this.data.images.join(",")
    }
    let callBack = {
      onNext: res => {
        this.showXToast({ title: `评价成功`, icon: 'yes' })
        setTimeout(() => wx.navigateBack(), 1200)
      },
      onCompleted: () => this.showLoading(false)
    }
  
    api.post('orderComment', params, callBack)
    
  }, showXToast: function (toast) {
    toast.show = true
    this.setData({ xToast: toast })
    let that = this
    setTimeout(() => {
      that.setData({ ['xToast.show']: false })
    }, 1200)
  },
  showLoading: function (show) {
    this.setData({ isLoading: show })
  }
})